package com.ll.admin.realm;

import com.ll.admin.service.IMemberService;
import com.ll.admin.vo.Member;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Map;
import java.util.Set;

public class MemberRealm extends AuthorizingRealm {
    @Reference
    private IMemberService memberService ;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.err.println("【2】｛MemberRealm｝************** 用户授权处理 **************");
        Map<String, Set<String>> map = memberService.findPrivilegeByMember(SecurityUtils.getSubject().getSession().getAttribute("mid").toString());
        SimpleAuthorizationInfo authz = new SimpleAuthorizationInfo();
        authz.setRoles(map.get("allRoles"));
        authz.setStringPermissions(map.get("allActions"));
        return authz;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.err.println("【1】｛MemberRealm｝============== 用户认证处理 ==============");
        Member member = memberService.loginUserName(token.getPrincipal().toString()) ;
        if(member == null) {
            throw new UnknownAccountException("账户信息不存在！") ;
        }
        if(!member.getPassword().equals(new String((char[])token.getCredentials()))) {
            throw new IncorrectCredentialsException("错误的用户名或密码！") ;
        }
        if(member.getStatus().equals(1)) {
            throw new LockedAccountException(member.getName() + "账户已经被锁定！");
        }
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("mid",member.getMid());        //将用户id封装到Session中
        session.setAttribute("email",member.getEmail());    //将email封装到Session中
        session.setAttribute("name",member.getName());      //将name封装到Session中
        session.setAttribute("password",member.getPassword());//将password封装到Session中
        return new SimpleAuthenticationInfo(token.getPrincipal(),token.getCredentials(),this.getName());
    }
}
